﻿using System;
using nRoute.Components.Composition;
using nRoute.Utilities;

namespace nRoute.Mapping
{
    public class DefaultServicesLocator 
		: ResourceLocator, IIntializableResource
    {
        private readonly string _serviceName;
        private readonly InitializationMode _initializationMode;

        public DefaultServicesLocator(string serviceName, Type serviceType, Type implementationType, ILifetimeManager lifetimeManager, InitializationMode initializationMode)
            : base(serviceType, implementationType, lifetimeManager)
        {
            Guard.ArgumentNotNull(implementationType, "serviceType");
            Guard.ArgumentNotNull(implementationType, "implementationType");

            _serviceName = (!string.IsNullOrEmpty(serviceName)) ? serviceName : implementationType.FullName;
            _initializationMode = initializationMode;
        }

#region Properties

        public string ServiceName
        {
            get { return _serviceName; }
        }

        public InitializationMode InitializationMode
        {
            get { return _initializationMode; }
        }

#endregion

#region IIntializableResource

        bool IIntializableResource.CanInitialize(ITypeBuilder typeBuilder)
        {
            return true;
        }

        void IIntializableResource.Initialize(ITypeBuilder typeBuilder)
        {
            if (_initializationMode == InitializationMode.OnDemand)
            {
                this.CreateResourceInstance(typeBuilder);
            }
        }

#endregion

    }
}